package com.business_clean.app.uitl;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.util.TimeUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import me.hgj.mvvmhelper.ext.LogExtKt;

/**
 * 下载文件到外部存储的工具类
 */
public class DownloadUtil {

    private static final Object LOCK = new Object();

    public interface DownloadListener {
        void onDownloadProgress(int progress);

        void onDownloadSuccess(File file);

        void onDownloadFailed(Exception e);
    }

    public static void downloadFile(String url, String suffix, String customFileName, boolean useLocalFile, DownloadListener listener) {
        new DownloadTask(url, suffix, customFileName, useLocalFile, listener).execute();
    }

    private static class DownloadTask extends AsyncTask<Void, Integer, File> {
        private String mUrl;
        private String mSuffix;
        private String mCustomFileName;
        private boolean mUseLocalFile;
        private DownloadListener mListener;

        DownloadTask(String url, String suffix, String customFileName, boolean useLocalFile, DownloadListener listener) {
            mUrl = url;
            mSuffix = suffix;
            mCustomFileName = customFileName;
            mUseLocalFile = useLocalFile;
            mListener = listener;
        }

        @Override
        protected File doInBackground(Void... params) {
            File file = null;
            try {
                // 如果允许使用本地文件,先检查是否存在
                if (mUseLocalFile) {
                    file = getLocalFile(mUrl, mSuffix);
                    if (file != null && file.exists()) {
                        Log.e("下载", "是本地文件");
                        return file;
                    }
                }

                // 下载文件
                file = downloadFileFromUrl(mUrl, mSuffix);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return file;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mListener.onDownloadProgress(values[0]);
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (file != null) {
                mListener.onDownloadSuccess(file);
            } else {
                mListener.onDownloadFailed(new Exception("Download failed"));
            }
        }

        private File getLocalFile(String url, String suffix) {
            // 构建本地文件路径
            File localFile = new File(Environment.getExternalStorageDirectory(), getFileName(url, mCustomFileName));
            return localFile;
        }

        private File downloadFileFromUrl(String url, String suffix) throws IOException {
            // 下载文件并保存到外部存储的公共 Downloads 目录
            File targetDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File targetFile = new File(targetDir, getFileName(url, mCustomFileName));

            // 加锁以保证线程安全
            synchronized (LOCK) {
                URL downloadUrl = new URL(url);
                HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection();
                connection.connect();

                int fileLength = connection.getContentLength();

                try (InputStream input = connection.getInputStream();
                     OutputStream output = new FileOutputStream(targetFile)) {
                    byte[] buffer = new byte[4096];
                    int count;
                    int downloaded = 0;
                    while ((count = input.read(buffer)) != -1) {
                        output.write(buffer, 0, count);
                        downloaded += count;
                        publishProgress((int) (downloaded * 100 / fileLength));
                    }
                }
            }

            return targetFile;
        }

        private String getFileName(String url, String mCustomFileName) {
            String fileName = "";
            // 提取后缀
            String fileSuffix = getFileSuffixFromUrl(url);
            fileName = mCustomFileName + fileSuffix;
            LogExtKt.logE("这里是下载1 - " + fileName, "");
            return fileName;
        }

        private String getFileNameFromUrl(String url) {
            // 从 URL 中提取文件名
            return Uri.parse(url).getLastPathSegment();
        }

        private String getFileSuffixFromUrl(String url) {
            // 从 URL 中提取文件后缀
            String fileName = getFileNameFromUrl(url);
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex != -1) {
                return fileName.substring(dotIndex);
            }
            return "";
        }
    }
}